package fa7.socialcode.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import fa7.socialcode.dao.NoticiaDao;
import fa7.socialcode.model.Noticia;

public class NoticiaDaoJpa implements NoticiaDao {

	private static EntityManagerFactory factory;
	static {
		factory = Persistence.createEntityManagerFactory("socialcode");
	}

	private EntityManager entityManager;

	private EntityManager getEntityManager() {
		if (entityManager == null)
			entityManager = factory.createEntityManager();
		return entityManager;
	}

	public List findNoticias() {
		return getEntityManager().createQuery("from Noticia").getResultList();
	}

	public void removeNoticia(Noticia noticia) {
		getEntityManager().getTransaction().begin();

		getEntityManager().remove(noticia);

		getEntityManager().getTransaction().commit();
	}

	public void removeNoticia(Long id) {
		getEntityManager().getTransaction().begin();

		getEntityManager().remove(findNoticia(id));

		getEntityManager().getTransaction().commit();
	}

	public void saveNoticia(Noticia noticia) {
		getEntityManager().getTransaction().begin();
		if (noticia.getId() != null) {
			getEntityManager().merge(noticia);
		} else {
			getEntityManager().persist(noticia);
		}

		getEntityManager().getTransaction().commit();
	}

	public Noticia findNoticia(Long id) {
		return getEntityManager().find(Noticia.class, id);
	}
}
